package com.kch.web.controller.system;

import com.github.pagehelper.PageHelper;
import com.kch.common.annotation.Log;
import com.kch.common.core.controller.BaseController;
import com.kch.common.core.domain.AjaxResult;
import com.kch.common.core.page.TableDataInfo;
import com.kch.common.enums.BusinessType;
import com.kch.common.utils.DateUtils;
import com.kch.framework.util.ShiroUtils;
import com.kch.system.domain.AuditRecord;
import com.kch.system.domain.SysBusiness;
import com.kch.system.domain.SysTag;
import com.kch.system.req.BusinessReq;
import com.kch.system.service.AuditRecordService;
import com.kch.system.service.ContentService;
import com.kch.system.service.ISysBusinessService;
import com.kch.system.service.ISysTagService;
import com.kch.system.vo.AuditRecordVO;
import com.kch.system.vo.SysBusinessVO;
import com.kch.system.vo.SysTagResp;
import com.kch.web.config.CloumnProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.fasterxml.jackson.databind.ObjectWriter.Prefetch.empty;

/**
 * 业务咨询
 */
@Controller
@RequestMapping("/system/business")
@Api(tags = "业务管理")
public class SysBusinessController extends BaseController {
    private String prefix = "system/business";

    @Autowired
    private ISysTagService sysTagService;
    @Autowired
    private ISysBusinessService sysBusinessService;
    @Autowired
    private CloumnProperties cloumnProperties;
    @Autowired
    private AuditRecordService auditRecordService;
    @Autowired
    private ContentService contentService;

    @RequiresPermissions("system:business:view")
    @GetMapping()
    public String index(ModelMap mmap) {
        // cloumnProperties.getBusiness()
        mmap.put("tags", contentService.getTagList(cloumnProperties.getTepro(), true));
        return prefix + "/business";
    }

    @PostMapping("/list")
    @RequiresPermissions("system:business:list")
    @ResponseBody
    public TableDataInfo list(SysBusiness business) {
        startPage();
        List<SysBusinessVO> list = sysBusinessService.selectListPage(business);
        return getDataTable(list);
    }

    @GetMapping("/status")
    @RequiresPermissions("system:business:list")
    @ResponseBody
    public AjaxResult status(Integer id) {
        try {
            sysBusinessService.updateStatus(id);
            return toAjax(true);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @GetMapping("/add")
    public String add(ModelMap mmap) {
//        List<SysTag> sysTags = sysTagService.selectByCloumnCode(cloumnProperties.getBusiness());
//        Map<String, List<SysTag>> collect = sysTags.stream().collect(Collectors.groupingBy(SysTag::getCloumnCode));
//        List<SysTag> empty = new ArrayList<>();
        List<SysTagResp> sysTags = contentService.getTagList(cloumnProperties.getTepro(), true);
        for(String code: cloumnProperties.getBusiness()){
            mmap.put(code + "tags", sysTags);
        }
        return prefix + "/add";
    }

    @Log(title = "咨询管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Validated SysBusiness sysBusiness) {
        checkBusiness(sysBusiness);
        sysBusiness.setCreateBy(ShiroUtils.getLoginName());
        sysBusiness.setUserId(ShiroUtils.getUserId().intValue());
        sysBusiness.setStatus("1");
        sysBusiness.setType("1");
        sysBusiness.setReviewStatus("2");
        sysBusinessService.insertSysBusiness(sysBusiness);
        return toAjax(true);
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, ModelMap mmap) {
        mmap.put("bus",sysBusinessService.selectById(id));
        return prefix + "/edit";
    }

    @GetMapping("/out")
    public String out(ModelMap mmap) {
//        List<String> outs = new ArrayList<>();
//        outs.add(cloumnProperties.getOutbusxq());
//        outs.add(cloumnProperties.getOutbuswt());
        mmap.put("tags", contentService.getTagList(cloumnProperties.getTepro(), true));
        return prefix + "/out/business";
    }

    @GetMapping("/out/add/{type}")
    public String outAdd(@PathVariable("type") String type, ModelMap mmap) {
        List<SysTagResp> sysTags = contentService.getTagList(cloumnProperties.getTepro(), true);
        List<String> outs = new ArrayList<>();
        if("1".equals(type)){
            outs.add(cloumnProperties.getOutbusxq());
            //sysTags = sysTagService.selectByCloumnCode(outs);
            mmap.put("type", "XQ");
        }
        if("2".equals(type)){
            outs.add(cloumnProperties.getOutbuswt());
            //sysTags = sysTagService.selectByCloumnCode(outs);
            mmap.put("type", "WT");
        }
        mmap.put("tags", sysTags);
        return prefix + "/out/add";
    }

    @Log(title = "字典类型", businessType = BusinessType.INSERT)
    @PostMapping("/out/add")
    @ResponseBody
    public AjaxResult outAdd(@Validated SysBusiness sysBusiness) {
        checkOutBusiness(sysBusiness);
        sysBusiness.setCreateBy(ShiroUtils.getLoginName());
        sysBusiness.setUserId(ShiroUtils.getUserId().intValue());
        sysBusiness.setType("2");
        sysBusiness.setReviewStatus("0");
        sysBusinessService.insertSysBusiness(sysBusiness);

        //添加审核表
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(sysBusiness.getId());
        auditRecord.setBusType("2");
        auditRecord.setReviewStatus("0");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion("待审核");
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);
        return toAjax(true);
    }

    @PostMapping("/out/list")
    @ResponseBody
    public TableDataInfo outList(SysBusiness business) {
        business.setUserId(ShiroUtils.getUserId().intValue());
        startPage();
        List<SysBusiness> list = sysBusinessService.selectOutListPage(business);
        return getDataTable(list);
    }

    @Log(title = "咨询管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(sysBusinessService.deleteBusiness(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @GetMapping("/out/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        SysBusinessVO sysBusinessVO = sysBusinessService.selectById(id);
        //List<String> collect = Stream.of(sysBusinessVO.getCloumnCode()).collect(Collectors.toList());
        mmap.put("tags", contentService.getTagList(cloumnProperties.getTepro(), true));
        mmap.put("bus", sysBusinessVO);
        return prefix + "/out/edit";
    }

    @Log(title = "咨询", businessType = BusinessType.UPDATE)
    @PostMapping("/out/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysBusiness sysBusiness) {
        checkOutBusiness(sysBusiness);
        try {
            SysBusiness exist = sysBusinessService.selectSysById(sysBusiness.getId());
            sysBusiness.setUpdateBy(ShiroUtils.getLoginName());
            sysBusiness.setUpdateTime(new Date());
            sysBusiness.setCreateTime(exist.getCreateTime());
            sysBusiness.setCreateBy(exist.getCreateBy());
            sysBusiness.setUserId(exist.getUserId());
            sysBusiness.setType(exist.getType());
            sysBusiness.setReviewStatus(exist.getReviewStatus());
            BeanUtils.copyProperties(sysBusiness, exist);
            return toAjax(sysBusinessService.updateById(exist));
        }catch (Exception e){
            return toAjax(false);
        }
    }

    @GetMapping("/out/detail/{id}")
    public String outDetail(@PathVariable("id") Integer id, ModelMap mmap) {
        SysBusinessVO sysBusinessVO = sysBusinessService.selectById(id);
        List<String> collect = Stream.of(sysBusinessVO.getCloumnCode()).collect(Collectors.toList());
        mmap.put("tags", contentService.getTagList(cloumnProperties.getTepro(), true));
        mmap.put("bus", sysBusinessVO);
        return prefix + "/out/detail";
    }


    @GetMapping("/out/audit/index")
    public String outAudit(ModelMap mmap) {
        List<String> outs = new ArrayList<>();
        outs.add(cloumnProperties.getOutbusxq());
        outs.add(cloumnProperties.getOutbuswt());
        mmap.put("tags", contentService.getTagList(cloumnProperties.getTepro(), true));
        return prefix + "/audit/business";
    }

    @PostMapping("/out/audit/list")
    @ResponseBody
    public TableDataInfo outAuditList(SysBusiness business) {
        startPage();
        List<SysBusiness> list = sysBusinessService.selectOutListPage(business);
        return getDataTable(list);
    }

    @GetMapping("/audit/{id}")
    public String audit(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        return prefix + "/audit/audit";
    }

    @PostMapping("/audit")
    @ResponseBody
    public TableDataInfo auditList(@RequestParam("id") Integer id) throws Exception {
        if(ObjectUtils.isEmpty(id)){
            List<AuditRecordVO> auditRecords = new ArrayList<>();
            return getDataTable(auditRecords);
        }
        startPage();
        List<AuditRecordVO> auditRecords = auditRecordService.selectByBusId(id, "2");
        return getDataTable(auditRecords);
    }

    @GetMapping("/audit/detail/{id}")
    public String auditDetail(@PathVariable("id") Integer id, ModelMap mmap) {
        SysBusinessVO sysBusinessVO = sysBusinessService.selectById(id);
        List<String> collect = Stream.of(sysBusinessVO.getCloumnCode()).collect(Collectors.toList());
        mmap.put("tags", contentService.getTagList(cloumnProperties.getTepro(), true));
        mmap.put("bus", sysBusinessVO);
        return prefix + "/audit/detail";
    }

    @GetMapping("/audit/pass/{id}")
    public String pass(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        mmap.put("userName", ShiroUtils.getLoginName());
        mmap.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        mmap.put("status", "审核通过");
        return prefix + "/audit/pass";
    }

    @Log(title = "审核通过", businessType = BusinessType.INSERT)
    @PostMapping("/audit/pass")
    @ResponseBody
    public AjaxResult pass(AuditRecordVO auditRecordVO){
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(auditRecordVO.getId());
        auditRecord.setBusType("2");
        auditRecord.setReviewStatus("1");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion(auditRecordVO.getOpinion());
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);

        SysBusiness exist = sysBusinessService.selectSysById(auditRecordVO.getId());
        exist.setReviewStatus("1");
        exist.setStatus("1");
        sysBusinessService.updateById(exist);
        return AjaxResult.success();
    }

    @GetMapping("/audit/fail/{id}")
    public String fail(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        mmap.put("userName", ShiroUtils.getLoginName());
        mmap.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        mmap.put("status", "审核不通过");
        return prefix + "/audit/fail";
    }

    @Log(title = "审核不通过", businessType = BusinessType.INSERT)
    @PostMapping("/audit/fail")
    @ResponseBody
    public AjaxResult fail(AuditRecordVO auditRecordVO){
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(auditRecordVO.getId());
        auditRecord.setBusType("2");
        auditRecord.setReviewStatus("2");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion(auditRecordVO.getOpinion());
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);

        SysBusiness exist = sysBusinessService.selectSysById(auditRecordVO.getId());
        exist.setReviewStatus("2");
        sysBusinessService.updateById(exist);
        return AjaxResult.success();
    }

    @PostMapping("/addBusiness")
    @ResponseBody
    @ApiOperation("咨询管理管理提问题和发需求,cloumnCode必填")
    public AjaxResult addBusiness(@RequestBody @Validated BusinessReq req){
        SysBusiness sysBusiness = new SysBusiness();
        BeanUtils.copyProperties(req, sysBusiness);
        sysBusiness.setCreateBy(ShiroUtils.getLoginName());
        sysBusiness.setUserId(ShiroUtils.getUserId().intValue());
        sysBusiness.setType("2");
        sysBusiness.setReviewStatus("0");
        sysBusinessService.insertSysBusiness(sysBusiness);

        //添加审核表
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(sysBusiness.getId());
        auditRecord.setBusType("2");
        auditRecord.setReviewStatus("0");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion("待审核");
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);
        return toAjax(true);
    }

    @GetMapping("/getBusiness")
    @ResponseBody
    @ApiOperation("小程序查询我的发布")
    public TableDataInfo getBusiness(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        return getDataTable( sysBusinessService.selectPageByUserId(ShiroUtils.getSysUser()));
    }

    private void checkBusiness(SysBusiness business){
        if("FA".equals(business.getCloumnCode())){
            //方案
            if(ObjectUtils.isEmpty(business.getPriceType())){
                throw new RuntimeException("价格类型不能为空");
            }else if("2".equals(business.getPriceType())){
                if(ObjectUtils.isEmpty(business.getPrice())){
                    throw new RuntimeException("金额类型为意向金额时，金额数不能为空");
                }
            }
            if(ObjectUtils.isEmpty(business.getImg())){
                throw new RuntimeException("封面图不能为空");
            }
        }
        if(Stream.of("XQ","WT").collect(Collectors.toList()).contains(business.getCloumnCode())){
            if(ObjectUtils.isEmpty(business.getPriceType())){
                throw new RuntimeException("价格类型不能为空");
            }else if("2".equals(business.getPriceType())){
                if(ObjectUtils.isEmpty(business.getPrice())){
                    throw new RuntimeException("金额类型为意向金额时，金额数不能为空");
                }
            }
            if(ObjectUtils.isEmpty(business.getRelease())){
                throw new RuntimeException("发布对象不能为空");
            }
        }
        if("ZJ".equals(business.getCloumnCode())){
            if(ObjectUtils.isEmpty(business.getRelease())){
                throw new RuntimeException("学校不能为空");
            }
            if(ObjectUtils.isEmpty(business.getPost())){
                throw new RuntimeException("相关岗位/学院不能为空");
            }
        }
    }

    private void checkOutBusiness(SysBusiness business){
        if(ObjectUtils.isEmpty(business.getPriceType())){
            throw new RuntimeException("价格类型不能为空");
        }else if("2".equals(business.getPriceType())){
            if(ObjectUtils.isEmpty(business.getPrice())){
                throw new RuntimeException("金额类型为意向金额时，金额数不能为空");
            }
        }
    }
}
